#pragma once
#include <iostream>
#include <cstdio>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "Task.hpp"

// 先描述
// 封装一个 "通道" 信息
class Channel
{
public:
    Channel(int fd, pid_t id) : _wfd(fd), _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }

    ~Channel() {};

    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        if (n != sizeof(code))
        {
            std::cerr << "write failed" << std::endl;
        }
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        int status;
        pid_t rid = waitpid(_subid, &status, 0);
        if (rid != _subid)
        {
            std::cerr << "waitpid failed" << std::endl;
        }
    }

    int Fd() { return _wfd; }
    pid_t SubId() { return _subid; }
    std::string Name() { return _name; }

private:
    int _wfd;          // 管道的写端文件描述符（父进程用于向子进程发送数据）
    pid_t _subid;      // 子进程的 PID
    std::string _name; // 通道的名称（格式为 channel-<wfd>-<subid>，便于调试）
};

// 再组织
// 管理所有的Channel对象，负责存储和打印通道信息。
class ChannelManager
{
public:
    ChannelManager() {}

    void Insert(int wfd, pid_t subid)
    {
        Channel c(wfd, subid);
        _channels.push_back(std::move(c));
    }

    Channel& Select()
    {
        auto& channel = _channels[_next];
        _next++;
        _next %= _channels.size();
        return channel;
    }

    ~ChannelManager() {};

    void PrintChannel()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }

    void StopSubProcess()
    {
        for (auto& channel : _channels)
        {
            channel.Close();
            std::cout << "关闭子进程" << channel.Name() << "的通道" << std::endl;
        }
    }

    void WaitSubProcess()
    {
        for (auto& channel : _channels)
        {
            channel.Wait();
            std::cout << "等待子进程" << channel.Name() << "退出" << std::endl;
        }
    }

private:
    std::vector<Channel> _channels;
    int _next = 0;
};

const int gdefaultnum = 5;

// 创建并管理一组子进程，通过管道实现父进程与子进程的通信。
class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num) 
    {
        _tm.Register(PrintLog);
        _tm.Register(DownLoad);
        _tm.Register(Upload);
    }

    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程" << getpid() << "收到一个任务码code: " << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程" << getpid() << "退出" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read failed" << std::endl;
                break;
            }
        }
    }

    bool Create()
    {
        for (int i = 0; i < _process_num; ++i)
        {
            // 1. 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            // 2. 创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // 子进程
                // 3.关闭不需要的文件描述符
                close(pipefd[1]);
                Work(pipefd[0]); // ???
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                // 3.关闭不需要的文件描述符
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
            }
        }
        return true;
    }

    void Debug()
    {
        _cm.PrintChannel();
    }

    void Run()
    {
        // 1.选择一个任务
        int taskcode = _tm.Code();
        std::cout << "选择一个任务码: " << taskcode << std::endl;
        // 2.选择信道(子进程), 负载均衡的选择信道, 完成任务
        auto& channel = _cm.Select();
        std::cout << "选择一个子进程: " << channel.Name() << std::endl;
        // 3.向信道写入任务码
        channel.Send(taskcode);
        std::cout << "向子进程" << channel.SubId() << "发送任务码: " << taskcode << std::endl;
    }

    void Stop()
    {
        // 关闭父进程所有wfd即可
        _cm.StopSubProcess();
        // 回收所有子进程
        _cm.WaitSubProcess();
    }

    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};
